package ca.kooki.codesnippet.views;

import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.*;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.SWT;

public class NewUserView extends ViewPart {
  
  //```````````````````````
  // MEMBER VARIABLES
  //```````````````````````

  public Label labelName;
  public Text inputName;
  public Label labelMessage;
  public Button buttonAdd;
  
  public Composite parent;
  
  //```````````````````````
  // CONSTRUCTOR
  //```````````````````````
  
  public NewUserView()
  {}
  
  //```````````````````````
  // INTERFACE
  //```````````````````````
  
  public void createPartControl(Composite parent) 
  {
    labelName = createLabel(parent,"User Name:");
    inputName = new Text(parent,SWT.LEFT | SWT.SINGLE | SWT.BORDER);
    
    skipEntry(parent);
    buttonAdd = new Button(parent,SWT.PUSH);
    buttonAdd.setText("Add");
    
    labelMessage = new Label(parent,SWT.LEFT);
    
    GridLayout viewLayout = new GridLayout();
    viewLayout.numColumns = 3;

    GridData layoutData = null;

    layoutData = new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.HORIZONTAL_ALIGN_END);
    labelName.setLayoutData(layoutData);

    layoutData = new GridData(GridData.FILL_HORIZONTAL);
    layoutData.horizontalSpan = 2;
    inputName.setLayoutData(layoutData);

    layoutData = new GridData(GridData.FILL_HORIZONTAL);
    labelMessage.setLayoutData(layoutData);

    NewUserViewHandler buttonHandler = new NewUserViewHandler(buttonAdd,inputName,labelMessage);
    inputName.addKeyListener(buttonHandler);
    addNewUserButtonListener(buttonHandler);
    
    parent.setLayout (viewLayout);
    this.parent = parent;
    
  }

  public void setFocus() {
    inputName.setFocus();
  }


  
  //```````````````````````
  // PRIVATE METHODS
  //```````````````````````

  private Label createLabel(Composite parent, String text)
  {
    Label myLabel = new Label(parent, SWT.RIGHT);
    myLabel.setText(text);
    return myLabel;
  }

  private void skipEntry(Composite parent)
  {
    Label empty = createLabel(parent,"");
    empty.setVisible(false);
  }
  
  private void addNewUserButtonListener(final NewUserViewHandler handler)
  {
    buttonAdd.addSelectionListener(new SelectionAdapter()
    {
      public void widgetSelected(SelectionEvent event)
      {
        handler.addNewUser();
      }
    }
    );
  }


}